import { parsePath } from "./parsePath";

/**
 * 创建一个 location 对象
 * @param {*} path 路径地址可能为字符串也可能为对象
 * @param {*} state 状态
 * @param {*} key state 对应 key 值
 * @param {*} currentLocation 当前 location 
 * @returns 
 */
export function createLocation(path, state, key, currentLocation) {
    let location;
    // 当路径传入为字符串时
    if (typeof path === 'string') {
        location = parsePath(path); // 解析地址字符串为对象形式
        location.state = state;
    } else {
        // 当路径传入为对象时
        location = Object.assign({}, path);
        // pathname
        (location.pathname === undefined) && (location.pathname = '');
        // search
        if (location.search) {
            (location.search.charAt(0) !== '?') && (location.search = '?' + location.search)
        } else {
            location.search = '';
        }
        // hash
        if (location.hash) {
            (location.hash.charAt(0) !== '#') && (location.hash = '#' + location.hash);
        } else {
            location.hash = '';
        }
        if (state !== undefined && location.state === undefined) location.state = state;
    }
    //? 以上通过边界处理得到 location 对象
    if (key) location.key = key;
    // 传入当前 location
    if (currentLocation) {
        if (!location.pathname) {
            location.pathname = currentLocation.pathname;
        }
    } else {
        if (!location.pathname) {
            location.pathname = '/';
        }
    }
    return location;
}
